package com.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import com.qbb.server.exception.HandlerException;

public class StartServerPort {
	private StartServerPort() {
	}

	/**
	 * 服务端绑定端口启动server服务
	 * 
	 * @param port
	 * @throws Exception
	 */
	public static void bind(int port) throws Exception {
		ServerBootstrap serverBootstrap = null;
		EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			serverBootstrap = new ServerBootstrap();// 引导辅助程序
			serverBootstrap.group(bossGroup, workerGroup)
					.channel(NioServerSocketChannel.class)
					.childHandler(new ServerChannelInitializer());
			// 绑定端口 同步等待绑定成功
			ChannelFuture f = serverBootstrap.bind(port).sync();
			// 等到服务端监听端口关闭
			f.channel().closeFuture().sync();
		} catch (Exception e) {
			HandlerException.error(e);
		} finally {
			workerGroup.shutdownGracefully();
			bossGroup.shutdownGracefully();
		}
	}
}
